<template>
  <dt-modal-edit
    ref="edit"
    :title="title"
    :width="900"
    @ok="onOk"
    @cancelData="cancelData"
    :cancelTip="cancelTip"
    alwaysTip>
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150">
      <div class="addCall">
        <Row :gutter="24">
          <Col span="12">
            <FormItem label="员工姓名：" prop="workNo" class="house_search">
              <Select
                v-model="formValidate.workNo"
                clearable
                filterable
                :disabled="type == 'edit'"
                :remote-method="getByWorkNoOrName"
                placeholder="请输入员工名或工号"
                @on-change="userChange">
                <Option v-for="(option, index) in optionsUser" :value="option.workNo" :key="index">
                  {{ `${option.userName}(${option.workNo})` }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="员工手机号：">
              <span>{{ (userInfo && userInfo.phone) || '-' }}</span>
            </FormItem>
          </Col>

          <Col span="12">
            <FormItem label="隐私号归属地：" prop="city">
              <Select
                v-if="type == 'add' && bindFlag != '2'"
                v-model="formValidate.city"
                clearable
                placeholder="请选择归属地"
                @on-change="cityChange">
                <Option v-for="(option, index) in cityList" :value="option" :key="index">
                  {{ option }}
                </Option>
              </Select>
              <Input v-else v-model="formValidate.city" disabled></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <div class="huan">
              <FormItem label="隐私号：" prop="phoneX">
                <Select
                  v-if="type == 'add' && bindFlag != '2'"
                  v-model="formValidate.phoneX"
                  placeholder="请选择呼出隐私号"
                  @on-change="phoneChange"
                  clearable>
                  <Option v-for="(option, index) in privacyPhoneList" :key="index" :value="option.phoneX">
                    {{ option.phoneX }}
                    <span v-if="option.bindFlag == 3">（保护期）</span>
                  </Option>
                </Select>
                <Input v-else v-model="formValidate.phoneX" disabled></Input>
              </FormItem>
              <span v-if="type == 'add' && bindFlag != '2'" @click="changeBatch('old')">换一批</span>
            </div>
          </Col>
        </Row>
        <Row :gutter="24" v-if="type == 'edit'">
          <Col span="12">
            <FormItem label="新隐私号归属地：" prop="newCity">
              <Select
                v-model="formValidate.newCity"
                clearable
                placeholder="请选择归属地"
                @on-change="cityChange1">
                <Option v-for="(option, index) in cityList" :value="option" :key="index">
                  {{ option }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <div class="huan">
              <FormItem label="新隐私号：" prop="newPrivacyPhone">
                <Select
                  v-model="formValidate.newPrivacyPhone"
                  placeholder="请选择呼出隐私号"
                  @on-change="phoneChange1"
                  clearable>
                  <Option v-for="(option, index) in privacyPhoneList" :key="index" :value="option.phoneX">
                    {{ option.phoneX }}
                  </Option>
                </Select>
              </FormItem>
              <span @click="changeBatch('new')">换一批</span>
            </div>
          </Col>
        </Row>
        <Row :gutter="24" v-if="type == 'add'">
          <Col span="12">
            <FormItem label="新增租期：">
              <Input v-model="formValidate.lease" disabled placeholder="请输入租期">
                <template #append>
                  <span>天</span>
                </template>
              </Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="新增通话时间：">
              <Input v-model="formValidate.minutes" disabled placeholder="请输入租期">
                <template #append>
                  <span>分钟</span>
                </template>
              </Input>
            </FormItem>
          </Col>
          <Col span="24">
            <div class="titS">当前状态：</div>
          </Col>
          <Col span="12">
            <FormItem label="租期剩余时间：">
              <span>{{ formValidate.surplusLease }}天</span>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="剩余通话时间：">
              <span>{{ $dt.tool.formatSeconds(formValidate.surplusMinutes) }}</span>
            </FormItem>
          </Col>
          <Col span="24">
            <div class="titS">新增后状态：</div>
          </Col>
          <Col span="12">
            <FormItem label="租期剩余时间：">
              <span>{{ formValidate.allLease }}天</span>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="剩余通话时间：">
              <span>{{ $dt.tool.formatSeconds(formValidate.allMinutes) }}</span>
            </FormItem>
          </Col>
        </Row>
      </div>
    </Form>
  </dt-modal-edit>
</template>

<script>
  // import addEdit from '../opt/addEdit'
  import caseMgr from '@/biz/crimeSceneList'
  import receiverMgr from '@/biz/receiver/receiver'
  import nameOpt from '@/biz/option/name.js'
  let setIN = null
  export default {
    data() {
      return {
        type: '',
        privacyPhoneList: [],
        cityList: [],
        optionsUser: [],
        title: '新增外呼套餐',
        formValidate: {
          newPrivacyPhone: '',
          newCity: '',
          workNo: null,
          userId: null,
          city: '',
          phoneX: '',
          surplusLease: 0,
          surplusMinutes: 0,

          lease: 30,
          minutes: 1500,

          allLease: 0,
          allMinutes: 0
        },
        userInfo: null,
        phoneInfo: null,
        privacyNumberId: '', //当前隐私号的id
        // cityInfo: null,
        ruleValidate: {
          phoneX: [{ required: true, message: '请选择隐私号', trigger: 'change' }],
          workNo: [{ required: true, message: '请选择员工', trigger: 'change' }],
          city: [{ required: true, message: '请选择隐私号归属地', trigger: 'change' }],
          newPrivacyPhone: [{ required: true, message: '请选择新隐私号', trigger: 'change' }],
          newCity: [{ required: true, message: '请选择新隐私号归属地', trigger: 'change' }]
        },
        phonePage: {
          page: 1,
          rows: 10
        },
        pages: '',
        currentPhoneX: null,
        //

        btnDisabled: true,
        delCaseBtnFlag: false,
        receiverDetails: null,
        cancelTip: '取消后会放弃该页面所有更改已保存操作，是否确认取消？',
        teamUserByRoleList: [],

        noEditFlag: true,
        oldFormValidate: {},

        cityAttrSort: [],
        optionsHouse: [],
        callInPhoneList: [],

        caseInfoBuilding: '',
        okText: 5,
        bindFlag: ''
      }
    },

    methods: {
      phoneChange(val) {
        console.log(val, 'vaaaaa')
        this.phoneInfo = val
      },
      phoneChange1(val) {
        console.log(val, 'vv')
        this.phoneInfo = val
      },
      // 城市选择
      cityChange(val) {
        if (val) {
          this.formValidate.city = val
          this.formValidate.phoneX = ''
          this.getCanBuyPhone(val)
        }
      },
      cityChange1(val) {
        if (val) {
          this.formValidate.newCity = val
          this.formValidate.newPrivacyPhone = ''

          this.getCanBuyPhone(val)
        }
      },
      getByWorkNoOrName(query) {
        return new Promise((resolve, reject) => {
          console.log(query, 'queryquery')
          if (query && query.indexOf(')') != '-1') {
            query = query.split('(')[1].split(')')[0]
          }
          if (query !== '') {
            receiverMgr.getByWorkNoOrName({ searchKey: query }).then((res) => {
              this.optionsUser = res
              resolve(this.optionsUser)
            })
          }
        })
      },
      userChange(id) {
        this.formValidate.city = ''
        this.formValidate.phoneX = ''
        this.formValidate.surplusLease = 0
        this.formValidate.surplusMinutes = 0
        if (id) {
          console.log(id, this.optionsUser, 'userChange')
          this.optionsUser.forEach((item) => {
            if (item.workNo === id) {
              this.userInfo = item
            }
          })
          if (this.userInfo && this.userInfo.userId) {
            this.toBuyPrivacyNumberPackage(this.userInfo.userId, this.userInfo.workNo)
          }
        }
      },

      // 检查人员是否有套餐
      toBuyPrivacyNumberPackage(id, workNo) {
        let params = {
          userId: id
        }
        receiverMgr.toBuyPrivacyNumberPackage(params).then((res) => {
          this.bindFlag = res.bindFlag

          this.privacyNumberId = res.privacyNumberId
          this.formValidate.userId = id
          this.formValidate.city = res.city

          this.formValidate.surplusLease = res.lease || 0
          this.formValidate.surplusMinutes = res.talkTimeSeconds || 0
          this.formValidate.allLease = this.formValidate.surplusLease + 30
          this.formValidate.allMinutes = this.formValidate.surplusMinutes + 90000 //1500分钟

          this.getCanBuyPhone(this.formValidate.city).then((data) => {
            let _index = this.privacyPhoneList.findIndex((item) => {
              return item.phoneX == res.phoneX
            })

            if (_index == '-1') {
              this.currentPhoneX = {
                phoneX: res.phoneX,
                id: res.privacyNumberId
              }
              if (this.type != 'edit' && data.bindFlag && data.bindFlag == 2) {
                this.privacyPhoneList.push(this.currentPhoneX)
              }
            } else {
              this.currentPhoneX = null
            }
            this.formValidate.workNo = this.userInfo.workNo
            this.formValidate.phoneX = res.phoneX

            this.phoneInfo = res.phoneX
          })
        })
      },
      // 城市类表
      getCityDictionaries() {
        receiverMgr.getCityDictionaries().then((res) => {
          this.cityList = res
        })
      },
      // 换一换
      changeBatch(newType) {
        ++this.phonePage.page
        if (this.pages < this.phonePage.page) {
          this.phonePage.page = 1
        }
        if (newType == 'new') {
          this.formValidate.newPrivacyPhone = ''
          this.getCanBuyPhone(this.formValidate.newCity).then((res) => {
            this.$Message.success('已更换')
          })
        } else {
          this.formValidate.phoneX = ''
          this.getCanBuyPhone(this.formValidate.city).then((res) => {
            this.$Message.success('已更换')
          })
        }
      },
      // 隐私号
      getCanBuyPhone(city) {
        return new Promise((resolve, reject) => {
          if (city) {
            let params = {
              city: city,
              page: this.phonePage.page,
              rows: this.phonePage.rows,
              userId: this.formValidate.userId
            }

            receiverMgr.getCanBuyPhone(params).then((res) => {
              this.pages = res.pages
              this.privacyPhoneList = res.list
              // if (this.currentPhoneX && this.type != 'edit') {
              //   this.privacyPhoneList.push(this.currentPhoneX)

              // }
              resolve(res.list)
            })
          }
        })
      },
      onOk() {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            let params = {}
            params.userId = this.userInfo.userId
            params.userName = this.userInfo.userName
            params.userPhone = this.userInfo.phone
            params.privateType = 'PURCHASE'

            params.city = this.formValidate.city
            params.phoneX = this.formValidate.phoneX

            let curr = this.privacyPhoneList.find((item) => {
              return item.phoneX == this.phoneInfo
            })
            if (curr) {
              params.privacyNumberId = curr.id
            } else {
              params.privacyNumberId = this.privacyNumberId
            }

            if (this.type == 'edit') {
              params.city = this.formValidate.newCity
              params.phoneX = this.formValidate.newPrivacyPhone
              params.privateType = 'REBINDING'
            } else {
              params.lease = 30
              params.minutes = 1500
            }

            this.$Modal.confirm({
              title: '提示',
              content: `确认添加所选套餐`,
              okText: '确认',
              closable: true,
              onOk: () => {
                receiverMgr.privacyNumberPackage(params).then((res) => {
                  this.$emit('dataRefresh')
                  this.$Message.success('成功')
                  this.$refs.edit.hide()
                  this.cancelData()
                })
              }
            })
          }
        })
      },

      show(type, val) {
        if (val) {
          console.log(val, 'show')
          let workNo = val.userName.split('(')[1].split(')')[0]
          this.userInfo = val
          this.userInfo.workNo = workNo
          this.userInfo.phone = val.userPhone
          this.getByWorkNoOrName(workNo).then((res) => {
            console.log(res, 'ccccc')
            this.userChange(val.userId)
          })
        }
        this.type = type
        this.$refs.edit.show()
        this.getCityDictionaries()
        this.$refs.formValidate.resetFields()
      },
      cancelData() {
        this.formValidate = {
          newPrivacyPhone: '',
          newCity: '',
          workNo: null,
          userId: null,
          city: '',
          phoneX: '',
          surplusLease: 0,
          surplusMinutes: 0,

          lease: 30,
          minutes: 1500,

          allLease: 0,
          allMinutes: 0
        }
        this.userInfo = null
        this.phoneInfo = null
        this.optionsUser = []
        this.$refs.formValidate.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .addCall {
    .huan {
      display: flex;
      flex-direction: row;
      line-height: 30px;

      span {
        margin-left: 10px;
        color: #2d8cf0;
        cursor: pointer;
      }
    }

    .titS {
      padding-bottom: 10px;
      font-weight: bold;
    }
  }
</style>
